﻿using System;
using System.Data.Linq;
using System.Linq;
using iHouse.Infrastructure;
using iHouse.Model.Data;
using iHouse.Model.Repository.Interface;

namespace iHouse.Model.Repository
{
    public class SqlBookRepository : BaseRepository<iHouseDbContext, Book>, IBookRepository
    {
        protected override string ContextKey
        {
            get { return "DataContextForBook"; }
        }

        protected override PaginationList<Book> GetDataByCategory(int categoryID, int pageIndex, int pageSize)
        {
            return (from i in CurrentDataContext.Books
                    where i.CategoryID == categoryID
                    orderby i.ID
                    select i)
                    .ToPaginationList(pageIndex, pageSize);
        }

        protected override PaginationList<Book> GetData(PagingCriteria criteria)
        {
            return (from i in CurrentDataContext.Books
                    orderby i.ID
                    select i)
                    .ToPaginationList(criteria);
        }

        public void CreateBook(Book book)
        {
            CurrentDataContext.Books.Add(book);
            CurrentDataContext.SaveChanges();
        }

        public void UpdateBook()
        {
            CurrentDataContext.SaveChanges();
        }

        public Book GetBookByID(int id)
        {
            return CurrentDataContext.Books.Where(book => book.ID == id).First();
        }

        public void DeleteBook(int id)
        {
            Book book = CurrentDataContext.Books.Single(e => e.ID == id);

            CurrentDataContext.Books.Remove(book);
            CurrentDataContext.SaveChanges();
        }

        public int GetBookCountByCategoryAndPage(int categoryID, int pageIndex, int pageSize)
        {
            if (pageIndex < 0)
                throw new ArgumentOutOfRangeException("index", pageIndex, "PageIndex cannot be below 0.");

            if (pageSize < 1)
                throw new ArgumentOutOfRangeException("pageSize", pageSize, "PageSize cannot be less than 1.");

            if (categoryID > 0)
            {

                return (from i in CurrentDataContext.Books
                        where i.CategoryID == categoryID
                        orderby i.ID
                        select i).ToPaginationList(pageIndex, pageSize).Count();
            }
            else
            {
                return (from i in CurrentDataContext.Books
                        orderby i.ID
                        select i).ToPaginationList(pageIndex, pageSize).Count();
            }
        }

        public int GetBookCount(int categoryID)
        {
            return CurrentDataContext.Books.Where(x => x.CategoryID == categoryID).Count();
        }
    }
}
